//
//  GFHomeViewController.m
//  GoodFood
//
//  Created by dllo on 15/10/28.
//  Copyright © 2015年 荣伟峰. All rights reserved.
//

#import "GFHomeViewController.h"

@interface GFHomeViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewAccessibilityDelegate>
@property (nonatomic, strong) GFHomeView *homePageTitleView;
@property (nonatomic, strong) GFHomeFlowLayout *homePageFlow;
@property (nonatomic, strong) UICollectionView *showCollectionView;
@property (nonatomic, strong) GFIntroViewController *intro;


#pragma mark _ 将model设为属性方便传值
@property (nonatomic, strong) GFHomeModel *hpModel1;
@property (nonatomic, strong) GFHomeModel *hpModel2;


#pragma mark _ 接收数据的字典或数组
@property (nonatomic, strong) NSMutableArray *titlePicArr;
@property (nonatomic, strong) NSMutableArray *downPicArr;
@property (nonatomic, strong) NSMutableArray *titleArr;
@property (nonatomic, strong) NSMutableArray *subTitleArr;

/* 加载标志 */
//@property (nonatomic, strong) WaitLoadView *WLView;

/* 缓存路径 */
@property (nonatomic, copy) NSString *titlePicPath;
@property (nonatomic, copy) NSString *downPicPath;



/* 判断网络状态 */
@property (nonatomic, assign) NSInteger status;
@end

@implementation GFHomeViewController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    UIView *view = (UIView *)[self.navigationController.view viewWithTag:10001];
    view.backgroundColor = [UIColor clearColor];
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.7];
    view.hidden = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden = NO;
}

//- (void)viewDidLoad {
//    [super viewDidLoad];
//    // Do any additional setup after loading the view.
//    
//    self.view.backgroundColor = [UIColor redColor];
//    
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"liebiao"] style:UIBarButtonItemStylePlain target:self action:@selector(showDraw:)];
//    self.navigationItem.leftBarButtonItem = leftItem;
//    
//}

- (void)showDraw:(UIBarButtonItem *)item {
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    YRSideViewController *sideViewController = [delegate sideVC];
    [sideViewController showLeftViewController:YES];
}

#pragma mark _ 处理网络数据
- (void)handleData {
    
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    /* 检测网络链接的单例, 网络变化时的回调方法 */
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        //        NSLog(@"网络状态 = %ld",status);
        
        self.status = status;
        
    }];
    
    
    
    
    
    [AFNetHandle GETWithURL:@"http://food.boohee.com/fb/v1/welcome" body:nil httpHead:nil responseStyle:JSON success:^(id result) {
        
        if (self.status == 1) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您现在属于移动数据上网，请注意流量" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:nil];
            [alert addAction:action];
            [self.navigationController presentViewController:alert animated:1 completion:nil];

            
            
        } else if (self.status == 2) {
            
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您现在处于wifi环境" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:nil];
            [alert addAction:action];
            [self.navigationController presentViewController:alert animated:1 completion:nil];
            
            
        }
        
        [self objectWriteToDisk:result withPathComponent:@"result1.plist"];
        
        NSArray *array = [result objectForKey:@"others"];
        
        self.titlePicArr = [NSMutableArray array];
        for (NSDictionary *dic in array) {
            self.hpModel1 = [GFHomeModel modWithDic:dic];
            [self.titlePicArr addObject:self.hpModel1];
            
        }
        
        [self creatHomePageTitleView];
        [self creatAddViewTarget];
        
        self.homePageTitleView.imageArr = self.titlePicArr;
        
        [self.showCollectionView reloadData];
        [self.overTimeView removeFromSuperview];
        [self.waitView removeFromSuperview];
        
    } fail:^(NSError *error) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"网络连接异常" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:action];
        [self.navigationController presentViewController:alert animated:1 completion:nil];
        
        [self.overTimeView removeFromSuperview];
        self.overTimeView = [[GFOverTimeView alloc] initWithFrame:self.view.frame withButtonBlock:^(UIButton *button) {
            [self.view addSubview:self.waitView];
            [self handleData];
        }];
        [self.waitView removeFromSuperview];
        [self.view addSubview:self.overTimeView];

    }];
    
    [AFNetHandle GETWithURL:@"http://food.boohee.com/fb/v1/topics" body:nil httpHead:nil responseStyle:JSON success:^(id result) {
        
        [self objectWriteToDisk:result withPathComponent:@"result2.plist"];
        
        NSArray *array = [result objectForKey:@"topics"];
        
        self.downPicArr = [NSMutableArray array];
        self.titleArr = [NSMutableArray array];
        self.subTitleArr = [NSMutableArray array];
        for (NSDictionary *dic in array) {
            [self.titleArr addObject:[dic objectForKey:@"title"]];
            [self.subTitleArr addObject:[dic objectForKey:@"sub_title"]];
            self.hpModel2 = [GFHomeModel modWithDic:dic];
            [self.downPicArr addObject:self.hpModel2];
        }
        [self.showCollectionView reloadData];
        [self.waitView removeFromSuperview];
        
    } fail:^(NSError *error) {
        [self.waitView removeFromSuperview];
    }];
}



#pragma mark - 判断有没有网络
- (void)netWorkingState {
    
    /**
     AFNetworkReachabilityStatusUnknown          = -1,  // 未知
     AFNetworkReachabilityStatusNotReachable     = 0,   // 无连接
     AFNetworkReachabilityStatusReachableViaWWAN = 1,   // 3G 花钱
     AFNetworkReachabilityStatusReachableViaWiFi = 2,   // 局域网络,不花钱
     */
    
    /* 检查网络状态管理者 单例 */
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    /* 检测网络链接的单例, 网络变化时的回调方法 */
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        //        NSLog(@"网络状态 = %ld",status);
        
    }];
    
}

#pragma mark - 设置本地存储(缓存)归档
- (void)objectWriteToDisk:(id)result withPathComponent:(NSString *)comStr {
    
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:comStr];
    
    [result writeToFile:path atomically:YES];
    
}

#pragma mark - 设置本地存储(缓存)反归档
- (id)getobjectFromDiskWithPath:(NSString *)path {
    
    NSDictionary *result = [NSDictionary dictionaryWithContentsOfFile:path];
    
    return result;
}




/* 创建首页轮播图 */
- (void)creatHomePageTitleView {
    self.homePageTitleView = [[GFHomeView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth / 375.0 * 420)];
    self.homePageTitleView.scrollView.delegate = self;
    [self.view addSubview:self.homePageTitleView];
    
}


#pragma mark _ 根据scrollView的滑块改变label的值
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.showCollectionView) {
        
        //        NSLog(@"%@", self.titleArr);
        
        int a = ((int)(self.showCollectionView.contentOffset.x) + ScreenWidth / 375 * 120) / (ScreenWidth / 375 * 120);
        if (a < 1) {
            a = 1;
        }
        self.homePageTitleView.titleLabel.text = self.titleArr[a - 1];
        self.homePageTitleView.contentLabel.text = self.subTitleArr[a - 1];
        
        
        //        NSLog(@"%f", self.showCollectionView.contentOffset.x);
    }
}



/* 创建下方展示图CollectionView */
- (void)creatShowCollectionView {
    self.homePageFlow = [[GFHomeFlowLayout alloc] init];
    
    self.showCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, ScreenWidth / 375 * 420, ScreenWidth, ScreenHeight - ScreenWidth / 375 * 420) collectionViewLayout:self.homePageFlow];
    self.showCollectionView.delegate = self;
    self.showCollectionView.dataSource = self;
    //    self.showCollectionView.pagingEnabled = YES;
    self.showCollectionView.backgroundColor = [UIColor colorWithRed:1.0 * 245.0 / 255.0 green:1.0 * 245.0 / 255.0 blue:1.0 * 245.0 / 255.0 alpha:1];
    
    /* 重用池 collection必须用重用池 */
    [self.showCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    [self.showCollectionView registerClass:[GFHomeShowCollectionViewCell class] forCellWithReuseIdentifier:@"HomePageShowCell"];
    
    [self.view addSubview:self.showCollectionView];
    [self.showCollectionView setContentOffset:CGPointMake(ScreenWidth / 375 * 5 + ScreenWidth / 375 * 120 * 1, 0)];
}



#pragma mark _ 展示区CollectionView DataSource协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 33;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    

    if (indexPath.item == 0 || indexPath.item == 32) {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
        
        
        return cell;
    } else {
        GFHomeShowCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomePageShowCell" forIndexPath:indexPath];
        cell.model = self.downPicArr[indexPath.item - 1];
        return cell;
    }
    
    
}



#pragma mark _ 展示区CollectionView Delegate协议方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.item != 0 && indexPath.item != 32) {
        GFHomeModel *model = [self.downPicArr objectAtIndex:indexPath.item - 1];
        self.intro = [[GFIntroViewController alloc] init];
        
        self.intro.idNumber = model.kill_id;
        self.intro.imageUrl = model.big_image_url;
        [self.navigationController pushViewController:self.intro animated:NO];
    }
    
    

}


#pragma mark _ 创建AddView的a/r设计模式
- (void)creatAddViewTarget {
    for (int i = 0; i < 10; i++) {
        self.homePageTitleView.addView = (GFBaseView *)[self.homePageTitleView viewWithTag:i + 10];
        self.homePageTitleView.addView.target = self;
        self.homePageTitleView.addView.action = @selector(clickedAddView:);
    }
}

- (void)clickedAddView:(GFBaseView *)view {
    
    GFDetialsViewController *details = [[GFDetialsViewController alloc] init];
    
    GFHomeModel *model = self.titlePicArr[view.tag - 10];
    
    details.food_code = model.food_code;
    
    [self.navigationController pushViewController:details animated:YES];
}

#pragma mark _ viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];

    [self netWorkingState];   
    
    //    [self creatHomePageTitleView];
    [self creatShowCollectionView];
    //    [self creatAddViewTarget];
    
    /* 创建加载标志 */
//    self.WLView = [[WaitLoadView alloc] initWithFrame:self.view.frame];
//    [self.view addSubview:self.WLView];
    [self.view bringSubviewToFront:self.waitView];
    [self handleData];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"liebiao"] style:UIBarButtonItemStylePlain target:self action:@selector(showDraw:)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
 
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sousuo"] style:UIBarButtonItemStyleDone target:self action:@selector(enterSearchViewController:)];
    self.navigationItem.rightBarButtonItem = rightItem;
    

    
    self.view.backgroundColor = [UIColor colorWithRed:1.0 * 245.0 / 255.0 green:1.0 * 245.0 / 255.0 blue:1.0 * 245.0 / 255.0 alpha:1];
    
    /* 定时器轮播图 */
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(turnPic) userInfo:nil repeats:YES];
    
    
    
    // Do any additional setup after loading the view.
}

#pragma mark _ navigationItem 的方法


/* 右侧呼叫搜索 */
- (void)enterSearchViewController:(UIBarButtonItem *)item {
    
    GFSearchFoodViewController *searchVC = [[GFSearchFoodViewController alloc] init];
    
    [self.navigationController pushViewController:searchVC animated:YES];
    

    
}


#pragma mark _ 定时器方法
- (void)turnPic {
    
    CGFloat a = ((NSInteger)(self.homePageTitleView.scrollView.contentOffset.x / ScreenWidth + 11) % 10) * ScreenWidth / 375 * 375;
    
    [self.homePageTitleView.scrollView setContentOffset:CGPointMake(a, 0) animated:NO];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
